from fastapi import APIRouter, HTTPException
from pydantic import BaseModel
from typing import Optional, Dict
from app.utils.response import ResponseWrapper as R

from app.services.cookie_manager import CookieConfigManager
from app.services.prompt_service import PromptConfigManager
from ffmpeg_helper import ensure_ffmpeg_or_raise
from app.gpt.prompt import load_prompts_from_config, BASE_PROMPT, LINK, AI_SUM, SCREENSHOT

router = APIRouter()
cookie_manager = CookieConfigManager()
prompt_manager = PromptConfigManager()


class CookieUpdateRequest(BaseModel):
    platform: str
    cookie: str


class PromptUpdateRequest(BaseModel):
    prompt_type: str
    content: str


@router.get("/get_downloader_cookie/{platform}")
def get_cookie(platform: str):
    cookie = cookie_manager.get(platform)
    if not cookie:
        return R.success(msg='未找到Cookies')
    return R.success(
        data={"platform": platform, "cookie": cookie}
    )


@router.post("/update_downloader_cookie")
def update_cookie(data: CookieUpdateRequest):
    cookie_manager.set(data.platform, data.cookie)
    return R.success(

    )

@router.get("/sys_health")
async def sys_health():
    try:
        ensure_ffmpeg_or_raise()
        return R.success()
    except EnvironmentError:
        return R.error(msg="系统未安装 ffmpeg 请先进行安装")

@router.get("/sys_check")
async def sys_check():
    return R.success()

@router.get("/get_all_prompts")
async def get_all_prompts():
    """获取所有提示词配置"""
    try:
        prompts = prompt_manager.get_all_prompts()
        return R.success(data=prompts)
    except Exception as e:
        return R.error(msg=f"获取提示词配置失败: {str(e)}")

@router.post("/update_prompt")
async def update_prompt(data: PromptUpdateRequest):
    """更新指定类型的提示词"""
    try:
        success = prompt_manager.update_prompt(data.prompt_type, data.content)
        if success:
            # 更新成功后，重新加载提示词
            load_prompts_from_config()
            return R.success(msg="提示词更新成功")
        else:
            return R.error(msg="无效的提示词类型")
    except Exception as e:
        return R.error(msg=f"更新提示词失败: {str(e)}")

@router.get("/get_default_prompts")
async def get_default_prompts():
    """获取默认提示词配置"""
    try:
        default_prompts = {
            "BASE_PROMPT": BASE_PROMPT,
            "LINK": LINK,
            "AI_SUM": AI_SUM,
            "SCREENSHOT": SCREENSHOT
        }
        return R.success(data=default_prompts)
    except Exception as e:
        return R.error(msg=f"获取默认提示词配置失败: {str(e)}")

@router.post("/reset_prompt")
async def reset_prompt(data: PromptUpdateRequest):
    """重置指定类型的提示词为默认值"""
    try:
        default_prompts = {
            "BASE_PROMPT": BASE_PROMPT,
            "LINK": LINK,
            "AI_SUM": AI_SUM,
            "SCREENSHOT": SCREENSHOT
        }
        
        if data.prompt_type not in default_prompts:
            return R.error(msg="无效的提示词类型")
            
        # 更新为默认值，忽略传入的content参数
        default_content = default_prompts[data.prompt_type]
        success = prompt_manager.update_prompt(data.prompt_type, default_content)
        if success:
            # 更新成功后，重新加载提示词
            load_prompts_from_config()
            return R.success(msg="提示词已重置为默认值")
        else:
            return R.error(msg="重置提示词失败")
    except Exception as e:
        return R.error(msg=f"重置提示词失败: {str(e)}")

@router.post("/reset_all_prompts")
async def reset_all_prompts():
    """重置所有提示词为默认值"""
    try:
        default_prompts = {
            "BASE_PROMPT": BASE_PROMPT,
            "LINK": LINK,
            "AI_SUM": AI_SUM,
            "SCREENSHOT": SCREENSHOT
        }
        
        for prompt_type, content in default_prompts.items():
            prompt_manager.update_prompt(prompt_type, content)
        
        # 更新成功后，重新加载提示词
        load_prompts_from_config()
        return R.success(msg="所有提示词已重置为默认值")
    except Exception as e:
        return R.error(msg=f"重置提示词失败: {str(e)}")

@router.post("/restore_default_prompts")
async def restore_default_prompts():
    """从备份文件恢复默认提示词"""
    try:
        success = prompt_manager.restore_from_backup()
        if success:
            return R.success(msg="已成功恢复默认提示词")
        else:
            return R.error(msg="恢复默认提示词失败，可能是备份文件不存在")
    except Exception as e:
        return R.error(msg=f"恢复默认提示词失败: {str(e)}")